//
//  JCWRegVC.swift
//  HengYouCai
//
//  Created by wll on 2017/12/27.
//  Copyright © 2017年 lwj. All rights reserved.
//  注册界面--代码


///图片验证码 手机验证码宽度
private let imageCodeW: CGFloat = 80

///眼睛宽度
private let eyeImageW: CGFloat = 40


import UIKit
import ReactiveSwift

class JCWRegVC: BaseViewController {
    
    ///手机号 用于发送验证码  从JCWLogInVC带过来
    var phoneNumber: String?

    deinit {
        debugPrint("JCWRegVC dealloc")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.createNav()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.createCV()
        
        self.monitorValue()
    }
    func createNav() {
        UIApplication.shared.statusBarStyle = .default
        self.navigationController?.navigationBar.isTranslucent = true
        self.navigationController?.navigationBar.setBackgroundImage(Image(), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.shadowImage = Image()
//        self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back_white")
//        self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "back_white")
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: Image(named: "back_white"),
                                                                style: .done,
                                                                target: self,
                                                                action: #selector(leftBarButtonItemClick))
        
        
        self.wl_navTitle("注册", titleColor: UIColor.white)
        //蛋疼的布局循环 bug 导致 颜色刷新不执行
        let titleLab = UILabel(frame: CGRect.zero)
        titleLab.textColor = UIColor.white
        titleLab.text = "注册"
        titleLab.sizeToFit()
        self.navigationItem.titleView = titleLab
    }
    
    func createCV() {
        
        self.view.addSubview(self.bottomBgImV)
        self.bottomBgImV.frame = CGRect(x: 0, y: 0, width: self.view.width_sd, height: self.view.width_sd*self.bottomBgImV.height_sd/self.bottomBgImV.width_sd)
        
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.logoImV)
        self.logoImV.centerX_sd = self.view.centerX_sd
        self.logoImV.top_sd = kJcwGetNavHeight() + 20.aw_wl
        //如果需要logo把下面这一行删掉即可
        self.logoImV.frame = CGRect(x: 0, y: kJcwGetNavHeight(), width: 0, height: 0)
        
        self.view.addSubview(self.imageCodeView)
        self.imageCodeView.frame = CGRect(x: JCWLogRegTFMargin, y: self.logoImV.bottom_sd + 30.aw_wl, width: self.view.width_sd-JCWLogRegTFMargin*2-imageCodeW, height: JCWLogRegTFH)
        
        self.view.addSubview(self.imageCodeBtn)
        self.imageCodeBtn.bounds = CGRect(x: 0, y: 0, width: imageCodeW, height: 33)
        self.imageCodeBtn.left_sd = self.imageCodeView.right_sd
        self.imageCodeBtn.centerY_sd = self.imageCodeView.centerY_sd + 7
        
        
        self.view.addSubview(self.messageCodeView)
        self.messageCodeView.frame = CGRect(x: JCWLogRegTFMargin, y: self.imageCodeView.bottom_sd, width: self.imageCodeView.width_sd, height: JCWLogRegTFH)
        
        self.view.addSubview(self.messageCodeBtn)
        self.messageCodeBtn.bounds = CGRect(x: 0, y: 0, width: imageCodeW, height: 33)
        self.messageCodeBtn.left_sd = self.messageCodeView.right_sd
        self.messageCodeBtn.centerY_sd = self.messageCodeView.centerY_sd + 7
        
        self.view.addSubview(self.pswView)
        self.pswView.frame = CGRect(x: JCWLogRegTFMargin, y: self.messageCodeView.bottom_sd, width: self.view.width_sd-JCWLogRegTFMargin*2-eyeImageW, height: JCWLogRegTFH)
        
        self.view.addSubview(self.eyeBtn)
        self.eyeBtn.bounds = CGRect(x: 0, y: 0, width: eyeImageW, height: 33)
        self.eyeBtn.left_sd = self.pswView.right_sd
        self.eyeBtn.centerY_sd = self.pswView.centerY_sd + 7
        
        self.view.addSubview(self.firendCodeView)
        self.firendCodeView.frame = CGRect(x: JCWLogRegTFMargin, y: self.pswView.bottom_sd, width: self.view.width_sd-JCWLogRegTFMargin*2, height: JCWLogRegTFH)
        
        self.view.addSubview(self.regBtn)
        self.regBtn.frame = CGRect(x: JCWLogRegTFMargin, y: self.bottomBgImV.bottom_sd+100.aw_wl, width: self.firendCodeView.width_sd, height: 44)
        
        self.view.addSubview(self.agreeBtn)
        //        self.agreeBtn.centerY_sd = self.agreeBookBtn.centerY_sd
        self.agreeBtn.left_sd = self.regBtn.left_sd
        self.agreeBtn.top_sd = self.regBtn.bottom_sd + 5
        self.agreeBtn.size_sd = CGSize(width: 15, height: 15)
        
        self.view.addSubview(self.agreeBookBtn)
//        self.agreeBookBtn.centerX_sd = self.view.centerX_sd + self.agreeBtn.width_sd/2.0
        self.agreeBookBtn.left_sd = self.agreeBtn.right_sd
        self.agreeBookBtn.centerY_sd = self.agreeBtn.centerY_sd
        
        self.view.addSubview(self.serverPhoneNumber)
        self.serverPhoneNumber.centerX_sd = self.view.centerX_sd

        self.serverPhoneNumber.bottom_sd = self.view.height_sd - 10.ah_wl - SafeAreaInsets_Bottom
        
        
    }
    
    //MARK:监控数据
    func monitorValue() {
        let imageCodeSignal = self.imageCodeView.tF.reactive.continuousTextValues.map { (text) -> Bool in
            return !text!.isEmpty
        }
        
        let messageCodeSignal = self.messageCodeView.tF.reactive.continuousTextValues.map { (text) -> Bool in
            return !text!.isEmpty
        }
        
        let pswSignal = self.pswView.tF.reactive.continuousTextValues.map { (text) -> Bool in
            return !text!.isEmpty
        }
        
        let agreeSignal = self.agreeBtn.reactive.controlEvents(.touchUpInside).map { (sender) -> Bool in
            return sender.isSelected
        }

        weak var weakSelf = self
        Signal.combineLatest(imageCodeSignal,messageCodeSignal,pswSignal,agreeSignal).map { (bor1,bor2,bor3,bor4) in
            return bor1 && bor2 && bor3 && bor4
            }.observeValues { (bor) in
                weakSelf?.regBtn.isUserInteractionEnabled = bor
                weakSelf?.regBtn.setBackgroundImage(UIImage(named: bor ?"login_btn":"login_btn_gray"), for: .normal)
        }
        
        //绑定之后先手动触发一次 默认同意操作
        self.agreeBtn.sendActions(for: .touchUpInside)
    }
    
    
    //MARK:按钮点击事件
    //返回按钮点击
    @objc fileprivate func leftBarButtonItemClick(){
        self.navigationController?.popViewController(animated: true)
    }
    ///刷新图片验证码
    @objc fileprivate func refreshImageCode(_ temp: UIButton) {
        if let url = URL(string: JCW_GenerateImage) {
            do {
                let imageData = try Data(contentsOf: url)
                temp.setBackgroundImage(UIImage(data: imageData), for: .normal)
            } catch  {
                temp.setBackgroundImage(UIImage(named: "imageCodeBtn"), for: .normal)
                debugPrint("imageData install fail")
            }
        }
    }
    //短信验证码事件
    @objc fileprivate func messageCodeBtnClick(sender: UIButton) {
        self.getMessageCode()
    }
    //眼睛事件
    @objc fileprivate func eyeBtnClick(sender: UIButton) {
        self.pswView.tF.isSecureTextEntry = !self.pswView.tF.isSecureTextEntry
        sender.isSelected = !sender.isSelected
    }
    //立即注册事件
    @objc fileprivate func regBtnClick(sender: UIButton) {
        self.regRequest()
    }
    //同意事件
    @objc fileprivate func agreeBtnClick(sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    //协议书事件
    @objc fileprivate func agreeBookBtnClick(sender: UIButton) {
        let vc = BannerWebViewVC(urlStr: JCW_RegisterProtocol, title: "用户注册协议")
        self.pushVC(vc)
    }
    //客服电话事件
    @objc fileprivate func serverPhoneNumberClick(sender: UIButton) {
        JCWCallTel(WLFileManager.readUserData(forKey: kPhone) as? String ?? "400-861-5908")
    }
    
    
    
    //MARK:懒加载
    ///logo
    fileprivate lazy var logoImV: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "login_logo"))
        temp.sizeToFit()
        return temp
    }()
    
    ///图片验证码视图
    fileprivate lazy var imageCodeView: JCWAlertTextFieldView = {
        let temp = JCWAlertTextFieldView("请输入图片验证码", "图片验证码", "login_pic",imageCodeW)
        return temp
    }()
    ///图片验证码按钮
    fileprivate lazy var imageCodeBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.adjustsImageWhenHighlighted = false
        self.refreshImageCode(temp)
        temp.addTarget(self, action: #selector(refreshImageCode), for: .touchUpInside)
        return temp
    }()
    ///短信验证码视图
    fileprivate lazy var messageCodeView: JCWAlertTextFieldView = {
        let temp = JCWAlertTextFieldView("请输入验证码", "手机验证码", "login_phonecode",imageCodeW)
        temp.tF.keyboardType = .numberPad
        return temp
    }()
    ///短信验证码按钮
    fileprivate lazy var messageCodeBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.adjustsImageWhenHighlighted = false
        temp.setTitle("获取验证码", for: .normal)
        temp.setTitleColor(UIColor.white, for: .normal)
        temp.titleLabel?.font = Font_WL(14)
        temp.addTarget(self, action: #selector(messageCodeBtnClick), for: .touchUpInside)
        return temp
    }()
    ///密码输入框视图
    fileprivate lazy var pswView: JCWAlertTextFieldView = {
        let temp = JCWAlertTextFieldView("请设置8-16位数字字母组合密码", "请设置6-16位数字字母组合密码", "login_password",eyeImageW)
        temp.tF.isSecureTextEntry = true
        return temp
    }()
    ///眼睛按钮
    fileprivate lazy var eyeBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setImage(UIImage(named: "self_biyan"), for: .normal)
        temp.setImage(UIImage(named: "self_zengyan"), for: .selected)
        temp.addTarget(self, action: #selector(eyeBtnClick), for: .touchUpInside)
        return temp
    }()
    ///邀请码视图
    fileprivate lazy var firendCodeView: JCWAlertTextFieldView = {
        let temp = JCWAlertTextFieldView("邀请码(可不填)", "邀请码", "login_Invitationcode")
        temp.tF.keyboardType = .numberPad
        return temp
    }()
    ///底部装饰
    fileprivate lazy var bottomBgImV: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "reg_bg"))
        temp.contentMode = .scaleAspectFill
        return temp
    }()
    ///立即注册按钮
    fileprivate lazy var regBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setBackgroundImage(UIImage(named: "login_btn_gray"), for: .normal)
        temp.isUserInteractionEnabled = false
        temp.adjustsImageWhenHighlighted = false
        temp.setTitle("立即注册", for: .normal)
        temp.titleLabel?.font = Font_WL(15)
        temp.addTarget(self, action: #selector(regBtnClick), for: .touchUpInside)
        return temp
    }()

    ///同意按钮
    fileprivate lazy var agreeBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.addTarget(self, action: #selector(agreeBtnClick), for: .touchUpInside)
        temp.setImage(UIImage(named: "recharge_invest_agre01"), for: .normal)
        temp.setImage(UIImage(named: "recharge_invest_agre"), for: .selected)
        temp.sizeToFit()
        return temp
    }()
    ///协议书按钮
    fileprivate lazy var agreeBookBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.addTarget(self, action: #selector(agreeBookBtnClick), for: .touchUpInside)
        let text: NSMutableAttributedString = NSMutableAttributedString(string: " 我已阅读并同意", attributes: [NSFontAttributeName:Font_WL(12),NSForegroundColorAttributeName:Normal_666Color])
        text.append(NSAttributedString(string: "《子壹财富用户注册协议》", attributes: [NSFontAttributeName:Font_WL(12),NSForegroundColorAttributeName:Normal_ThemeColor]))
        temp.setAttributedTitle(text, for: .normal)
        temp.sizeToFit()
        return temp
    }()
    ///客服电话
    fileprivate lazy var serverPhoneNumber: UIButton = {
        let temp = UIButton(type: .custom)
        temp.addTarget(self, action: #selector(serverPhoneNumberClick), for: .touchUpInside)
        let text: NSMutableAttributedString = NSMutableAttributedString(string: "收不到验证码？请拨打客服电话：", attributes: [NSFontAttributeName:Font_WL(12),NSForegroundColorAttributeName:Normal_999Color])
        text.append(NSAttributedString(string: WLFileManager.readUserData(forKey: kPhone) as? String ?? "400-861-5908", attributes: [NSFontAttributeName:Font_WL(12),NSForegroundColorAttributeName:Normal_ThemeColor]))
        temp.setAttributedTitle(text, for: .normal)
        temp.sizeToFit()
        return temp
    }()
}

//MARK:请求区域
extension JCWRegVC {
    
    ///立即注册
    fileprivate func regRequest() {
        self.view.jcw_showGifLoading()
        
        HYCNetService.register(withDict: ["channel":kChannel_app,"mobileCode":self.messageCodeView.tF.text ?? "","passwd":self.pswView.tF.text ?? "","mobile":self.phoneNumber ?? "","signCode":self.firendCodeView.tF.text ?? "","source":"20"], onSuccess: { (str) in
            //注册完直接登录
            self.logIn()
        }) { (code, errMsg) in
            //失败刷新图片验证码
//            self.refreshImageCode(self.imageCodeBtn)
            self.view.showHUDFailTips(errMsg, hideDelay: kHUDHideDelay)
        }
    }
    
    ///获取短信验证码
    fileprivate func getMessageCode() {
        self.view.jcw_showGifLoading()
        HYCNetService.getMobileCode(withDict: ["mobile":self.phoneNumber ?? "","captcha":self.imageCodeView.tF.text ?? ""], onSuccess: { (str) in
            self.view.hideHUDLoading(0)
            //倒计时开启
            wl_timeCountDown(60, {
                self.messageCodeBtn.isUserInteractionEnabled = false
                self.messageCodeBtn.setTitleColor(Normal_666Color, for: .normal)
            }, { (timeCount) in
                self.messageCodeBtn.setTitle("\(timeCount)秒后重试", for: .normal)
            }) {
                self.messageCodeBtn.setTitleColor(UIColor.white, for: .normal)
                self.messageCodeBtn.isUserInteractionEnabled = true
                self.messageCodeBtn.setTitle("再次获取", for: .normal)
            }
        }) { (code, errMsg) in
            //失败刷新图片验证码
            self.refreshImageCode(self.imageCodeBtn)
            self.view.showHUDFailTips(errMsg, hideDelay: kHUDHideDelay)
        }
    }
    
    fileprivate func logIn() {
        //登录
        HYCNetService.login(withDict: ["userAccount":self.phoneNumber ?? "","passwd":self.pswView.tF.text ?? "","token":WLFileManager.readUserData(forKey: "GetuiClientId")], onSuccess: { (result) in
            //登录成功缓存sessionId
            WLFileManager.saveUserData(result?["sessionId"], forKey: kUserSessionId)
            //登陆成功获取用户信息
            HYCNetService.getUserInfoSuccess({ (resultDic) in
                self.view.hideHUDLoading(0)
                //缓存用户信息
                let dic: Dictionary? = resultDic?["result"] as? Dictionary<String,Any>
                WLFileManager.saveUserData(dic?["cusCode"], forKey: kCusCode)
                WLFileManager.saveUserData(dic?["cardStatus"], forKey: kCardStatus)
                WLFileManager.saveUserData(dic?["userIdCard"], forKey: kUserIdCard)
                WLFileManager.saveUserData(dic?["userRealname"], forKey: kUserRealname)
                WLFileManager.saveUserData(dic?["userPaypassword"], forKey: kUserPaypassword)
                WLFileManager.saveUserData(dic?["realnameStatus"], forKey: kRealnameStatus)
                WLFileManager.saveUserData(dic?["userAccount"], forKey: kUserAccount)
                WLFileManager.saveUserData(dic?["userLevel"], forKey: kUserLevel)
                WLFileManager.saveUserData(KRegistSuccess, forKey: KRegistSuccess)
                
                self.dismissVC()
            }, andFailed: { (c, e) in
                //获取用户信息失败
                self.view.showHUDFailTips(e, hideDelay: kHUDHideDelay)
            })
        }, andFailed: { (code, errorMsg) in
            //登录失败
            self.view.showHUDFailTips(errorMsg, hideDelay: kHUDHideDelay)
        })
    }
}
